package com.yoona.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yoona.common.enums.CommonEnums;
import com.yoona.common.response.BaseResponse;
import com.yoona.common.utils.JwtUtil;
import com.yoona.sms.SmsService;
import com.yoona.system.entity.SysUser;
import com.yoona.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: yoonada
 * @email: m15602498163@163.com
 * @create: 2020-11-08 17:18
 * @description: 管理员控制层
 */
@Api(tags = "管理员")
@CrossOrigin
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdminController {

    private final SmsService smsService;
    private final SysUserMapper sysUserMapper;
    private final JwtUtil jwtUtil;

    @ApiOperation("管理员手机验证码登录")
    @PostMapping("/adminLoginByMobilePhoneNumber")
    public BaseResponse<Object> adminLoginByMobilePhoneNumber(@RequestParam("mobilePhoneNumber") String mobilePhoneNumber, @RequestParam("verificationCode") String verificationCode){
        BaseResponse<Object> response = smsService.checkVerificationCode(mobilePhoneNumber, verificationCode);
        if (response.getCode()==CommonEnums.CHECK_VERIFICATION_CODE_SUCCESS.getCode()){
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", mobilePhoneNumber);
            SysUser sysUser = this.sysUserMapper.selectOne(wrapper);
            return BaseResponse.success(CommonEnums.WE_CHAT_LOGIN_SUCCESS, getToken(sysUser));
        }
        return response;
    }

    /**
     * 生成用户的token
     * @param user
     * @return
     */
    private String getToken(SysUser user) {
        Map<String,Object> userMap = new HashMap<>(3);
        userMap.put("uid",user.getUid());
        userMap.put("open_id",user.getOpenId());
        userMap.put("nick_name",user.getNickName());
        return jwtUtil.generateToken(userMap);
    }

}
